package com.yq.homework.day28;

import java.io.*;

/**
 * @author 3307235355@qq.com
 * @since 2022/06/27 20:09
 * * 使用多线程实现方式一 ,
 * * 多个文件一起复制功能(3个线程复制3个文件)，
 * * 并在控制台显示复制的进度，进度以百分比表示
 * * 例如：
 * * 把文件A复制到E盘某文件夹下，
 * * 在控制台上显示“XXX文件已复制xx%”，
 * * “XXX文件已复制xxx%”……“
 * * XXX文件已复制xxx%”，“XXX复制完成！”
 */
public class Demo02 {
    public static void main(String[] args) throws IOException {
        MyThread t1 = new MyThread("线程1111", new File("a.txt"), new File("copy_a.txt"));
        MyThread t2 = new MyThread("线程2222", new File("b.txt"), new File("copy_b.txt"));
        MyThread t3 = new MyThread("线程3333", new File("c.txt"), new File("copy_c.txt"));
        t1.start();
        t2.start();
        t3.start();
    }
}


class MyThread extends Thread {
    private File file;
    private File file1;

    public MyThread(String name, File file, File file1) {
        super(name);
        this.file = file;
        this.file1 = file1;
    }

    @Override
    public void run() {
        String name = getName();
        copyFile(name);
    }

    public void copyFile(String name) {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file1);
            in = new FileInputStream(file);
            // double count = 0;
            // int readData;
            // while ((readData = in.read()) != -1) {
            //     out.write(readData);
            //     double v = count++ / (float) file.length();
            //     String s = String.format("%.2f%n", v);
            //     System.out.println(name + "----" + file + "已经复制了" + Double.parseDouble(s) + "%");
            // }
            double count = 0;
            byte[] bytes = new byte[10];
            int readData;
            while ((readData = in.read(bytes)) != -1) {
                out.write(bytes,0,readData);
                double v = (count) / (float) file.length();
                count+=10;
                String s = String.format("%.2f%n", v);
                System.out.println(name + "----" + file + "已经复制了" + Double.parseDouble(s) + "%");
            }
            if ((readData = in.read()) == -1) {
                System.out.println(name + "===============" + file + "已经复制完成！！！");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null && out != null) {
                try {
                    out.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}